<template>
	<view>
		<block>
			<uni-nav-bar @clickLeft="goBack" status-bar="true" shadow="true" left-icon="back" left-text="返回" title="绑定登录账号"></uni-nav-bar>
		</block>

		<view class="uni-form-item ">
			<view class="title">手机号</view>
			<input v-model="temphone" @focus="getFocus(0)" class="uni-input " v-bind:class="{ 'input-error': hasError[0] }"
			 placeholder="请输入手机号" />
		</view>
		<button v-if="isActivateSession" class="button" type="primary" @click="goLogin">绑定微信账号</button>
	</view>
</template>

<script>
	import uniNavBar from "@/components/uni-nav-bar/uni-nav-bar.vue"
	import config from "@/common/config.js"
	export default {
		components: {
			uniNavBar
		},
		data() {
			return {
				temphone: '',
				password: '',
				hasError: [false, false],
				isActivateSession: false,
				sessionkey: ''
			}
		},
		methods: {
			onLoad() {
				//检查weixin的session是否过期
				uni.checkSession({
					success: (e) => {
						this.sessionkey = uni.getStorageSync(config.sessionkey);
						if (this.sessionkey.length != 0) {
							this.isActivateSession = true; 
						}
					},
					fail: () => {
						this.isActivateSession = false;
					}
				})
			},
			goLogin() {
				if (this.temphone.length == 0) {
					this.hasError.splice(0, 1, true);
					return;
				}
				if (this.isActivateSession) { //绑定手机号并登录
					var url = config.baseUrl + '/thirdbind/binduser';
					var data = {
						name: this.temphone,
						sessionkey: this.sessionkey
					};
					uni.request({
						method: 'POST',
						url: url, 
						data: data,
						header: {
							'content-type': 'application/json', //自定义请求头信息
							// 'Authorization':config.token//通过登录接口，生成新的token
						},
						success: (res) => {
							var statusCode = res.statusCode;
							console.log(statusCode);
							if (200 == statusCode) {
								//保存token
								console.log(res.data.token);
								uni.setStorageSync(config.token, res.data.token);
								uni.setStorageSync(config.telephoneKey,this.temphone);
								uni.showToast({
									title: "1绑定账号并登录成功",
									duration: 2000,
								});
								uni.switchTab({
								    url: '/pages/index/index'
								});
							}else if(402 == statusCode){
								//case1:ctx.throw(402, '手机号不存在，请重新输入或用密码登录');
								//case2:ctx.throw(402, '微信的sessionkey不存在，请用密码登录');
								
							}
							
							else {
								uni.showToast({
									title: "2绑定账号并登录失败",
									duration: 2000,
								});
							}
						},
						fail: (res) => {
							uni.showToast({
								title: "绑定账号并登录失败"
							});
						}
					});
				} else { //跳转到账号密码登录页面
					uni.navigateTo({
						url:'../loginnew/loginnew'
					})

				}
			},
			getFocus(indxe) {
				this.hasError.splice(indxe, 1, false);
			},
			goBack() {
				uni.navigateBack({

				})
			}
		}
	}
</script>

<style>
	.input-error {
		border: 2upx solid #FF3333;
	}
</style>
